import os
from PIL import Image
import uuid


def resize_image_min_side(input_path, min_side_length=300, save_dir="./upload"):
    """
    检查图片最小边是否小于指定长度，如果小于则等比放大到该长度。

    :param input_path: 输入图片路径
    :param min_side_length: 最小边长度，默认300px
    :param save_dir: 保存目录，默认为"./upload"
    :return: (success: bool, output_path: str, error_message: str)
    """
    try:
        # 打开图片
        with Image.open(input_path) as img:
            width, height = img.size
            min_side = min(width, height)

            # 如果最小边已经大于等于要求的长度，则直接返回原路径
            if min_side >= min_side_length:
                return True, input_path, ""

            # 计算放大比例
            scale = min_side_length / min_side
            new_width = int(width * scale)
            new_height = int(height * scale)

            # 等比放大图片
            resized_img = img.resize((new_width, new_height), Image.LANCZOS)

            # 确保保存目录存在
            os.makedirs(save_dir, exist_ok=True)

            # 生成新的文件名
            filename = f"{uuid.uuid4()}_{os.path.basename(input_path)}"
            output_path = os.path.join(save_dir, filename)

            # 保存图片
            # 如果图片模式是RGBA或者P且有透明度，保存为PNG以保留透明度
            if resized_img.mode in ('RGBA', 'LA') or (resized_img.mode == 'P' and 'transparency' in resized_img.info):
                if not output_path.lower().endswith('.png'):
                    output_path = output_path.rsplit('.', 1)[0] + '.png'
                resized_img.save(output_path, 'PNG')
            else:
                # 转换为RGB模式并保存为JPEG
                rgb_img = resized_img.convert('RGB')
                if not output_path.lower().endswith(('.jpg', '.jpeg')):
                    output_path = output_path.rsplit('.', 1)[0] + '.jpg'
                rgb_img.save(output_path, 'JPEG')

            return True, output_path, ""
    except Exception as e:
        return False, "", str(e)